package org.btik.light.mobile.ui.setting;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import androidx.annotation.Nullable;
import org.btik.context.SimpleContext;
import org.btik.light.mobile.R;


import static org.btik.light.mobile.platform.conf.AppConfig.LIGHT_SERVER_HOST;
import static org.btik.light.mobile.platform.conf.AppConfig.NAME_SPACE_LIGHT_HANDLER;

/**
 * @author lustre
 * @since 2023/4/29 16:49
 */
public class SetServerHostActivity extends Activity {
    public static final String NAME = "SetServerHost";
    private SharedPreferences sharedPreferences;

    private EditText serverHost;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.set_server_host);
        sharedPreferences = getSharedPreferences(NAME_SPACE_LIGHT_HANDLER, Context.MODE_PRIVATE);
        String lightServerHost = sharedPreferences.getString(LIGHT_SERVER_HOST, "");

        serverHost = findViewById(R.id.server_host);
        serverHost.setText(lightServerHost);
        serverHost.requestFocus();
        serverHost.setSelection(serverHost.length());
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        findViewById(R.id.ok).setOnClickListener(this::saveSeverHost);
        findViewById(R.id.back).setOnClickListener((v -> {
            setResult(RESULT_CANCELED, new Intent());
            finish();
        }));
    }

    private void saveSeverHost(View view) {
        SharedPreferences.Editor edit = sharedPreferences.edit();
        String serverHostValue = serverHost.getText().toString().trim();
        edit.putString(LIGHT_SERVER_HOST, serverHostValue);
        edit.apply();
        SimpleContext.set(LIGHT_SERVER_HOST, serverHostValue);
        Intent intent = new Intent();
        setResult(RESULT_OK, intent);
        finish();
    }


}
